package com.molichuxing.gateway.api.services.impl;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.molichuxing.gateway.api.services.AlipayApiService;
import com.molichuxing.gateway.bff.order.services.OrderBffService;
import com.molichuxing.gateway.bff.payment.services.UnionpayBffService;
import com.molichuxing.services.business.dto.response.NotifyBizDto;
import com.molichuxing.services.property.PaymentResultEnum;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "银联支付回调api")
@RestController
@RequestMapping(value = "/unionpay")
public class UnionApiServiceImpl extends RootApiService implements AlipayApiService {
	private static final Logger logger = LoggerFactory.getLogger(UnionApiServiceImpl.class);

	@Resource
	private UnionpayBffService unionpayBffService;

	@Resource
	private OrderBffService orderBffService;

	@Override
	@ApiOperation(value = "银联支付结果通知")
	@PostMapping(value = "/notify/pay")
	public String notifyPay(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 从支付宝回调的request域中取值获取支付宝返回的参数集合
			Map<String, String> res = new HashMap<String, String>();
			Enumeration<?> temp = request.getParameterNames();
			if (null != temp) {
				while (temp.hasMoreElements()) {
					String en = (String) temp.nextElement();
					String value = request.getParameter(en);
					res.put(en, value);
					// 在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
					if (res.get(en) == null || "".equals(res.get(en))) {
						res.remove(en);
					}
				}
			}
			logger.info("[notifyPay]银联支付结果: ({})", res);
			if (res == null || res.isEmpty()) {
				return "fail";
			}
			NotifyBizDto notifyBizDto = unionpayBffService.modifyNotifyPay(res);
			if (PaymentResultEnum.SUCCESS.equals(notifyBizDto.getPayResult())) {
				// 成功，修改订单信息(异步)
				orderBffService.modifyOrderPay(notifyBizDto);
			}

			return "success";
		} catch (Exception e) {
			logger.error("银联支付结果通知异常:", e);
			return "fail";
		}
	}
}
